const net = require('net');
const libcu = require('libcu');
const SUCCESS = 0;
class AvenirMQ {
    constructor() {
        this.sign = null;
        this.ip = null;
        this.port = null;
    }

    async init(info) {
        this.ip = info.ip;
        this.port = info.port;
    }

    //登录获取签名
    async login(info) {
        let sendText = {
            type: 'login',
            data: {
                name: info.name,
                password: libcu.cipher.AesEncode(info.password),
            }
        }
        let res = await this.asyncSend(sendText, 'login');
        return res;
    }

    async send(data, sign) {
        let sendText = {
            type: 'send',
            sign: sign || this.sign,
            data: data
        }
        let res = await this.asyncSend(sendText, 'send');
        return res;
    }


    //封装的发送函数
    async asyncSend(json, type) {
        let promise = new Promise((resolve, reject) => {
            let client = new net.Socket();  //后期改缓存连接
            client.connect({
                host: this.ip,
                port: this.port
            })

            //客户端与服务器建立连接触发
            client.on('connect', () => {
                client.write(JSON.stringify(json));
            });

            //客户端接收数据触发
            client.on('data', (data) => {
                client.end();
                let res = JSON.parse(data);
                if (res.code === SUCCESS && type === 'login') {
                    this.sign = res.data;
                }
                resolve(JSON.parse(data));
            });

            client.on('error', (error) => {
                reject(error);
            })
        })
        return promise;
    }

    //receive会启动一个服务，收到数据后会调用传进来的参数
    async receive(info, func) {
        let { ip, port } = info;
        if(!ip || !port) {
            throw ('Object[info] must contain ip and port');
        }

        if(!func) {
            throw ('lack of callback func');
        }
        this.server = new net.createServer();
        this.server.on('connection', async (client) => {

            client.on('data', async (msg) => { 
                //接收client发来的信息
                func(JSON.parse(msg));
            });

            client.on('error', function (e) { 
                //监听客户端异常
                console.log('client error:' + e);
                client.end();
            });

            client.on('close', function () {

            });

        });
        this.server.listen(port, ip, function () {

        });
    }
}

module.exports = AvenirMQ;
